package com.epro.dx.activity;

import java.util.ArrayList;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListView;

import com.epro.dx.R;
import com.epro.dx.adapter.BrowseListAdapter;
import com.epro.dx.enable.NetworkBroadcastReceiver;
import com.epro.dx.enable.NetworkBroadcastReceiver.NetWorkCallBack;
import com.epro.dx.pullview.PullToRefreshBase;
import com.epro.dx.pullview.PullToRefreshBase.Mode;
import com.epro.dx.pullview.PullToRefreshBase.OnRefreshListener2;
import com.epro.dx.pullview.PullToRefreshListView;
import com.epro.dx.task.BaseNeedReLoginTask;
import com.epro.dx.util.ActivityUtil;
import com.epro.dx.util.AsyncTaskUtil;
import com.epro.dx.util.GlobalConfig;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
import com.weipu.common.DXApplication;
import com.weipu.common.DXApplication.TrackerName;
import com.weipu.common.constants.Constant;
import com.weipu.common.constants.ServerConstant;
import com.weipu.common.facade.exception.DxException;
import com.weipu.common.facade.factory.ProviderFactory;
import com.weipu.common.facade.model.OrderProductModel;
import com.weipu.common.facade.model.WishModel;
import com.weipu.common.util.AlertToast;
import com.weipu.common.util.Logger;
import com.weipu.common.util.NetWorkUtil;
import com.weipu.common.util.StringUtil;

/**
 * 我的收藏
 *
 * @author Administrator
 * @version [版本号, 2015-3-2]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
public class FavoritesActivity extends BaseFragmentActivity implements OnItemClickListener, NetWorkCallBack,
    OnRefreshListener2<ListView>, OnItemLongClickListener
{
    /**
     * 适配器
     */
    private BrowseListAdapter listAdapter;
    
    private ArrayList<WishModel> pageModels;
    
    ArrayList<OrderProductModel> arrayList;
    
    /**
     * 开始数据索引位置
     */
    private int pageIndex = 1;
    
    PullToRefreshListView pullToRefreshListView;
    
    private boolean isLoadContinue = true;

	private Tracker tracker;
    
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        //集成GA
        tracker = ((DXApplication)getApplication()).getTracker(TrackerName.APP_TRACKER);
        //未登录
        if (!ActivityUtil.isLogin(this))
        {
            gotoLogin(false);
            return;
        }
        
        setContentView(R.layout.activity_wish);
        setTitleContent(R.string.favorites_title);
        setLeftBtnToHome(HomeActivity.titleArray[3]);
        pullToRefreshListView = (PullToRefreshListView)findViewById(R.id.data_list);
        pullToRefreshListView.setScrollingWhileRefreshingEnabled(true);
        pullToRefreshListView.setOnRefreshListener(this);
        pullToRefreshListView.setOnItemClickListener(this);
        pullToRefreshListView.getRefreshableView().setOnItemLongClickListener(this);
        
        NetworkBroadcastReceiver.setCallBack(this);
        //showWaitingDialog();
        //new LoadWishListTask(pageIndex).execute();
        //excuteTask(pageIndex);
        showLoadingLayout(pullToRefreshListView);
        AsyncTaskUtil.executeTask(new LoadWishListTask(pageIndex));
    }
    
    @Override
	protected void onResume() {
		super.onResume();
		tracker.setScreenName("MyWishList");
		tracker.send(new HitBuilders.ScreenViewBuilder().build());
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		tracker.setScreenName(null);
	}
    
    /**
     * 跳转登录界面
     * @return void [返回类型说明]
     * @exception throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    private void gotoLogin(boolean isNeedNotice)
    {
        Intent intent = new Intent(this, LoginActivity.class);
        Bundle data = new Bundle();
        //设置当前Activity action
        data.putInt(ServerConstant.Parameter.PARAMETER_NAME_LOGIN_ACTION_TYPE,
            ServerConstant.Parameter.PARAMETER_ACTION_TYPE_WISH);
        intent.putExtras(data);
        startActivity(intent);
        finish();
    }
    
    /**  
     * 转换数据类型
     * @see [类、类#方法、类#成员]
     */
    private void changeData()
    {
        for (WishModel model : pageModels)
        {
            OrderProductModel productInfo = new OrderProductModel();
            
            productInfo.setSku(model.getSku());
            productInfo.setShortHeadLine1(model.getProductInfo().getShortHeadLine());
            productInfo.setPrice((float)model.getProductInfo().getPrice());
            productInfo.setlistprice((float)model.getProductInfo().getListPrice());
            productInfo.setProductRating((float)model.getProductInfo().getProductRating());
            productInfo.setReviewCount(model.getProductInfo().getReviewCount());
            productInfo.setSmallPictureURL(model.getProductInfo().getSlideShowPictureThumbURL());
            productInfo.setCurrencyCode(model.getCurrencyCode());
            productInfo.setCurrencyCodeSymbol(model.getCurrencyCodeSymbol());
            arrayList.add(productInfo);
        }
        
    }
    
    public void onItemClick(AdapterView<?> parent, View view, int position, long id)
    {
        OrderProductModel orderProductModel = (OrderProductModel)listAdapter.getItem(position - 1);
        String name=StringUtil.getConfig(this,
				ServerConstant.Parameter.PARAMETER_NAME_USER_ACCOUNT);
        int sku=orderProductModel.getSku();
        if(!StringUtil.isContainKey(sku+"")){
        	StringUtil.saveConfig(sku+"", name);
        }
        Intent intent = new Intent(FavoritesActivity.this, DetailActivity.class);
        Bundle data = new Bundle();
        data.putInt(ServerConstant.Parameter.PARAMETER_NAME_PRODUCT_ID, sku);
        data.putString(ServerConstant.Parameter.PARAMETER_NAME_FROM_ACTIVITY, ServerConstant.ActionConstant.ACTION_WISH);
        intent.putExtras(data);
        startActivity(intent);
        
    }
    
    @Override
    public void netWorkChangeCallBack(boolean isLoadMore)
    {
        if (isLoadMore)
        {
            if (null != listAdapter)
            {
                listAdapter.notifyDataSetChanged();
                pullToRefreshListView.onRefreshComplete();
                isLoadContinue = Boolean.TRUE;
            }
        }
    }
    
    /** 
     *  获取收藏夹
     * @version [版本号, 2013-3-26]
     * @see [相关类/方法]
     * @since [产品/模块版本]
     * 
     * @author hjd008
     */
    protected class LoadWishListTask extends BaseNeedReLoginTask
    {
        
        private int start;
        
        public LoadWishListTask(int start)
        {
            this.start = start;
        }
        
        @Override
        protected void onPreExecute()
        {
        }
        
        @Override
        protected String doInBackground(Void... params)
        {
            String userName = null;
            try
            {
                //获取收藏夹
                userName =
                    StringUtil.getConfig(FavoritesActivity.this, ServerConstant.Parameter.PARAMETER_NAME_USER_ACCOUNT);
                
                pageModels =
                    ProviderFactory.createUserServiceProvider().wishListInfoForUser(userName,
                        "0",
                        start,
                        Constant.LIST_PAGE_COUNT,
                        ActivityUtil.getCustomerID(),ActivityUtil.getCustomerToken());
            }
            catch (DxException e)
            {
                return e.getErrCode();
            }
            catch (Exception e)
            {
                Logger.e("WishListFragment", "getData", e);
            }
            return "0";
        }
        
        @Override
        protected void onPostExecute(String result)
        {
        	super.onPostExecute(result);
        	if(!isFinishing()){
        		 if (1 == start)
                 {
                     //hideWaitingDialog();
//        			 loadingLayout.setVisibility(View.GONE);
        			 hideAllLayout(pullToRefreshListView);
                 }
                 if ("0".equals(result))
                 {
                     if (null!=pageModels&&pageModels.size() > 0)
                     {
                         if (1 == start)
                         {
                             pullToRefreshListView.setVisibility(View.VISIBLE);
                             arrayList = new ArrayList<OrderProductModel>();
                             changeData();
                             listAdapter = new BrowseListAdapter(FavoritesActivity.this, arrayList,pullToRefreshListView,null,false,getDensityDpi(),NetWorkUtil.isWifi(getApplicationContext()));
                             pullToRefreshListView.setAdapter(listAdapter);
                             pullToRefreshListView.onRefreshComplete();
                         }
                         else
                         {
                             changeData();
                             listAdapter.notifyDataSetChanged();
                         }
                     	pullToRefreshListView.onRefreshComplete();

                         //集合中的数据是否小于列表每次加载数据数量
                         if (pageModels.size() < Constant.LIST_PAGE_COUNT)
                         {
                         	pullToRefreshListView.setMode(Mode.PULL_FROM_START);
//                             isLoadContinue = false;
                         }
                         else
                         {
                         	pullToRefreshListView.setMode(Mode.BOTH);
                            // isLoadContinue = true;
                         }
                     }
                     else
                     {
                    	 pullToRefreshListView.onRefreshComplete();
                         if (1 == start)
                         {
                        	 showEmptyLayout(pullToRefreshListView, R.string.empty_wish_list, R.drawable.no_wish);
                         }
                         else
                         {
                         	pullToRefreshListView.setMode(Mode.PULL_FROM_START);
                             listAdapter.notifyDataSetChanged();
                         }
                     }
                 }
                 else if(!isRelogin)
                 {
                     //加载第一页因网络未连接或者超时显示网络异常页面
                     if (1 == start
                         /*&& (TextUtils.equals(ServerConstant.ReturnCode.CLIENT_NET_UN_AVAILABLE, result) 
                         		|| TextUtils.equals(ServerConstant.ReturnCode.VALIDATOR_CONNECT_TIMEOUT,
                             result))*/)
                     {
                    	 if(ServerConstant.ReturnCode.CLIENT_NET_UN_AVAILABLE.equals(result)){
 							showErrorLayout(pullToRefreshListView, R.string.internet_error,
 									R.string.internet_suggest, R.drawable.no_internet);
 						}else{
 							showErrorLayout(pullToRefreshListView, R.string.server_busy,
 									R.string.server_suggest, R.drawable.no_internet);
 						}
                    	 retryBtn.setOnClickListener(new OnClickListener()
                         {
                             @Override
                             public void onClick(View v)
                             {
                            	 showLoadingLayout(null);
                                 //new LoadWishListTask(pageIndex).execute();
                                 //excuteTask(pageIndex);
//                            	 if(null!=listAdapter){
//                            		 listAdapter.setIsFirst(true);
//                            	 }
                                 AsyncTaskUtil.executeTask(new LoadWishListTask(pageIndex));
                             }
                         });
                     }
                     else
                     {
                     	pullToRefreshListView.onRefreshComplete();
                     	pullToRefreshListView.setMode(Mode.BOTH);
                     	pageIndex--;
                         AlertToast.alert(FavoritesActivity.this, ServerConstant.ReturnCode.MESSAGEMAP.get(result));
                     }
                 }
        	}
           
        }

		@Override
		protected Context setContext() {
			return FavoritesActivity.this;
		}

		@Override
		protected BaseNeedReLoginTask setTask() {
			return new LoadWishListTask(start);
		}
    }
    
    /**
     * 
     * 用来删除收藏夹中商品
     * 
     * @version [版本号, 2012-12-14]
     * @see [相关类/方法]
     * @since [产品/模块版本]
     * 
     * @author lzk176
     */
    protected class DeleteWishAsyncTask extends BaseNeedReLoginTask
    {
        private int position;
        
        private int sku;
        
        String userName;
        public DeleteWishAsyncTask(int sku, int position)
        {
            this.position = position;
            this.sku = sku;
        }
        
        @Override
        protected void onPreExecute()
        {
//            showWaitingDialog();
        	showLoadingLayout(null);
        }
        
        @Override
        protected String doInBackground(Void... params)
        {
            String result = "";
            try
            {
                userName =
                    StringUtil.getConfig(FavoritesActivity.this, ServerConstant.Parameter.PARAMETER_NAME_USER_ACCOUNT);
                result = ProviderFactory.createUserServiceProvider().delWishlistForUser(userName, sku,ActivityUtil.getCustomerToken());
            }
            catch (DxException e)
            {
                return e.getErrCode();
            }
            catch (Exception e)
            {
                Logger.e("WishListAdapter", "DeleteWishAsyncTask", e);
            }
            return result;
        }
        
        @Override
        protected void onPostExecute(String result)
        {
        	super.onPostExecute(result);
        	if(!isFinishing()){
//        		 hideWaitingDialog();
        		hideAllLayout(pullToRefreshListView);
                 if ("0".equals(result))
                 {
                     isLoadContinue = true;
                     pageIndex = 1;
                     listAdapter.removeItem(position);
                     if(listAdapter.getProductsSize()<=0){
                    	 pageIndex=1;
//                    	 listAdapter.setIsFirst(true);
//                    	 loadingLayout.setVisibility(View.VISIBLE);
                    	 showLoadingLayout(pullToRefreshListView);
                    	 AsyncTaskUtil.executeTask(new LoadWishListTask(pageIndex));
                     }
                 }
                 else if (result.equals(ServerConstant.ReturnCode.STATUS_NOT_LOGON + ""))
                 {
                     //未登录或登录超时需要跳转到登录界面
                     gotoLogin(true);
                 }
                 else if(!isRelogin)
                 {
                     AlertToast.alert(FavoritesActivity.this, ServerConstant.ReturnCode.MESSAGEMAP.get(result));
                 }
        	}
        	
           if("0".equals(result)){
        	   if(null!=userName&&userName.equals(StringUtil.getConfig(FavoritesActivity.this, sku+""))){
                	GlobalConfig.getInstance().setShoppingCartChange(true);
                	//设置为空表示删除该键值对
                	StringUtil.saveConfig(sku+"", null);
                }
           }
        }

		@Override
		protected Context setContext() {
			return FavoritesActivity.this;
		}

		@Override
		protected BaseNeedReLoginTask setTask() {
			return new DeleteWishAsyncTask(sku, position);
		}
        
    }
    
    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView)
    {
        pageIndex = 1;
        //new LoadWishListTask(pageIndex).execute();
       // excuteTask(pageIndex);
//        if(null!=listAdapter){
//        	listAdapter.setIsFirst(true);
//        }
        
        AsyncTaskUtil.executeTask(new LoadWishListTask(pageIndex));
        
    }
    
    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView)
    {
        if (isLoadContinue)
        {
            //new LoadWishListTask(++pageIndex).execute();
        	//excuteTask(++pageIndex);
        	 AsyncTaskUtil.executeTask(new LoadWishListTask(++pageIndex));
        }
        
    }
    
    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id)
    {
        final OrderProductModel cartItem = (OrderProductModel)listAdapter.getItem(position - 1);
        if(null==cartItem){
        	return true;
        }
        new AlertDialog.Builder(FavoritesActivity.this).setTitle(R.string.delete)
            .setCancelable(true)
            .setMessage(R.string.user_wish_confirm_del)
            .setPositiveButton(R.string.btn_title_ok, new DialogInterface.OnClickListener()
            {
                @Override
                public void onClick(DialogInterface dialog, int which)
                {
                    //new DeleteWishAsyncTask(cartItem.getSku(), position - 1).execute();
                	AsyncTaskUtil.executeTask(new DeleteWishAsyncTask(cartItem.getSku(), position - 1));
                }
            })
            .setNegativeButton(R.string.btn_title_cancel, new DialogInterface.OnClickListener()
            {
                @Override
                public void onClick(DialogInterface dialog, int which)
                {
                    dialog.cancel();
                }
            })
            .create()
            .show();
        return true;
    }
    
    @Override
    protected void onDestroy() {
    	NetworkBroadcastReceiver.setCallBack(null);
//    	if(null!=listAdapter){
//    		listAdapter.recleBitmap();
//    	}
    	super.onDestroy();
    }
}
